<?php

namespace app\admin\controller\yexam;

use app\admin\model\yexam\QuestionType;
use app\admin\model\yexam\SubjectCombo;
use app\common\controller\Backend;
use fast\Tree;
use think\Request;

/**
 * 科目管理
 *
 * @icon fa fa-circle-o
 */
class Subject extends Backend
{

    protected $noNeedRight = [''];
    protected $model = null;
    protected $categoryModel = null;
    protected $relationSearch = true;
    protected $searchFields = 'id,short_name,en_name';
    protected $questionTypeModel = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\yexam\Subject;
        $this->categoryModel = new \app\common\model\Category;
        $this->packageModel = new \app\admin\model\Package;
        // 试题类型
        $this->questionTypeModel = new \app\admin\model\yexam\ComboCategory();
    }

    public function index()
    {
        $categoryArr = collection($this->categoryModel->where('status', 'normal')->where('type','exam')->select())->toArray();
        $categoryMap = array_column($categoryArr, 'name', 'id');
        $categoryValid = array_keys($categoryMap);

        $packageArr = collection($this->packageModel->select())->toArray();
        $packageMap = array_column($packageArr, 'package_name', 'id');
        $packageCategoryMap = array_column($packageArr, 'category_id', 'id');

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $items = $list->items();
            $rows = [];
            $question = new \app\admin\model\yexam\Question();
            foreach ($items as $item) {
                $row = $item->toArray();

                $cid = (int)$row['category_id'];
                if (in_array($cid, $categoryValid)) {
                    $row['category_id'] = isset($categoryMap[$cid]) ? $categoryMap[$cid] . " (id:$cid)" : '-';
                } else {
                    $row['category_id'] = "⚠️ 有问题的分类 (id:$cid)";
                }

                $package_ids_info = '';
                $package_ids = explode(',', $row['package_ids']);
                $warning_package_ids = '';
                if ($package_ids) {
                    foreach ($package_ids as $package_id) {
                        // 检测班次是否是当前分类下的（针对可能数据库导数据出错的情况），如果不是给出针对可能
                        if (isset($packageCategoryMap[$package_id]) &&
                            $packageCategoryMap[$package_id] != $cid)
                        {
                            $warning_package_ids .= '{' . $package_id . '}';
                        }

                        $package_ids_info .= isset($packageMap[$package_id]) ?
                            ', '.$packageMap[$package_id] : '';
                    }
                    $row['package_ids'] = trim($package_ids_info, ', ');

                    // 允许使用上一级的package_id
                    //if ($warning_package_ids) {
                    //    $row['package_ids'] = $row['package_ids'];
                    //}
                }

                if ($row['content_json']) {
                    $row['content_json'] = '已设置「双击查看」';
                }

                $rows[] = $row;
            }
            foreach ($rows as $k => $r){
                $rows[$k]['free'] = $question->where('subject_id',$r['id'])->where('is_free',0)->count();
                $rows[$k]['total'] = $question->where('subject_id',$r['id'])->count();
            }


            $result = array("total" => $list->total(), "rows" => $rows);
            return json($result);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            parent::add();
        } else {
            $list = collection($this->categoryModel->where('status','normal')->where('type','exam')->select())->toArray();
            $tree = Tree::instance();
            $tree->init($list, 'pid');
            $categoryList = $tree->getTreeList($tree->getTreeArray(0), 'name');
            $categorydata = [];
            foreach ($categoryList as $k => $v)
            {
                $categorydata[$v['id']] = $v;
            }
            $questionTypeAll = $this->questionTypeModel->field('*')->select();
            $this->view->assign('questionType',$questionTypeAll);
            $this->view->assign("parentList", $categorydata);
            return $this->fetch();
        }
    }

    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if ($this->request->isPost()) {
            parent::edit($ids);
        } else {
            $list = collection($this->categoryModel->where('status','normal')->where('type','exam')->select())->toArray();
            $tree = Tree::instance();
            $tree->init($list, 'pid');
            $categoryList = $tree->getTreeList($tree->getTreeArray(0), 'name');
            $categorydata = [];
            foreach ($categoryList as $k => $v)
            {
                $categorydata[$v['id']] = $v;
            }
            // 获取所有的题型
            $questionTypeAll = $this->questionTypeModel->field("*")->select();
            foreach ($questionTypeAll as $key => $value)
            {
                $questionTypeAll[$key]['checked'] = $value['category_id'] == $row['question_category_id'] ? "selected" : "";
            }
            $this->view->assign("parentList", $categorydata);
            $this->view->assign("row", $row);
            $this->view->assign('questionType',$questionTypeAll);
            return $this->fetch();
        }
    }
    //=============== 查询题型
    public function getQuestionType()
    {
        $subjectId = $this->request->param('subject_id');
        $result = $this->model->where('id',$subjectId)->field('question_type')->value('question_category_id');
        $category = new \app\admin\model\yexam\ComboCategory();
        $result = $category->where('category_id',$result)->value('question_type');
        $type = [];
        $question = new QuestionType();
        $result = $question->where('questid','in',$result)->field('questype,questcode')->select();
        foreach ($result as $value)
        {
            array_push($type,['name' => $value->questype,'code' => $value->questcode]);
        }
        return json([
            'rows' => $type
        ]);
    }
}